// service/email/wx.go
package email

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"muziai-server/global"
)

type EmailService struct {
}

func (es EmailService) NewEmailClient() (d *gomail.Dialer, err error) {
	e := global.Config.Email
	d = gomail.NewDialer(e.Domain, e.Port, e.Email, e.AuthorizationCode)
	_, err = d.Dial()
	if err != nil {
		return
	}
	return
}

func (es EmailService) SendEmail(subject, to, body string) (err error) {
	e := global.Config.Email
	// 创建邮件消息
	m := gomail.NewMessage()
	m.SetHeader("From", e.Email)
	m.SetHeader("To", to)
	m.SetHeader("Subject", subject)
	m.SetBody("text/plain", body)
	client, err := es.NewEmailClient()
	if err != nil {
		return
	}
	err = client.DialAndSend(m)
	if err != nil {
		return err
	}
	return
}

// 发送注册验证码
func (es EmailService) SendRegisterCode(template string, to string, code string) error {
	site := global.Config.SiteInfo
	subjectTitle := "木子AI"
	if site.Site.Title != "" {

		subjectTitle = site.Site.Title
	}
	return es.SendEmail(fmt.Sprintf("【%s】", subjectTitle), to, fmt.Sprintf(template, code))
}
